<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>用户登陆</title>
  <script type="text/javascript" src="js/sha1.js"></script>
</head>

<body>
  <form id="loginForm" class="loginForm" action="server/login.php" method="post">
    <input type="text" name="username" value="" placeholder="请输入用户名">
    <input type="password" name="password" value="" placeholder="请输入密码">
    <label class="verifiCode"></label>
    <input type="text" name="verifiCode" value="" placeholder="输入验证码">
    <input type="submit" name="" value="登陆">
  </form>
</body>

<script type="text/javascript">
  /**
   * 页面载入完成时，显示验证码
   * 验证码通过ajax请求从后端获得
   */
  window.onload = function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET', 'server/verifiCode.php', true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var response = JSON.parse(xmlhttp.responseText);
        (document.getElementsByClassName('verifiCode')[0]).innerText = response.code;
      }
    };
  };

  /**
   * 用户点击登陆按钮时，对输入的密码进行加盐后hash，盐值即是验证码
   * 保证即使同一个用户，每次登陆，网络上所传输的密码密文都是不一样的，防止重放攻击
   */
  var form = document.getElementsByClassName('loginForm')[0];
  form.addEventListener('submit', function(event) {
    // 检测验证码输入是否正确
    var verifiCodeInput = document.getElementsByName('verifiCode')[0];
    var verifiCode = (document.getElementsByClassName('verifiCode')[0]).innerText.trim();
    if (verifiCodeInput.value != verifiCode) {
      alert('验证码输入错误,请刷新网页后重试!');
      event.preventDefault();
      return;
    }

    var password = (document.getElementsByName('password')[0]);
    // alert('不加入随机值的密码为: ' + hex_sha1(password.value));
    password.value = hex_sha1(hex_sha1(password.value) + verifiCode);
    alert('加入随机验证码之后的密码为: ' + password.value);
    form.submit();
  });
</script>

</html>